<!-- eslint-disable vue/valid-v-for -->
<template>
  <div class="page-container">
    <page-form :model="form" layout="vertical" div="true" ref="formRef">
      <card class="add-info-card" :title="pageType == 'edit' ? '编辑GPS' : '新增GPS'" toggle :showDivider="false">
        <page-form-row>
          <page-form-item
            field="vehicleNum"
            label="设备编号"
            required
            :rules="[{ required: true, message: '请填写设备编号', trigger: 'change' }]"
          >
            <i-input placeholder="请输入" v-model="form.vehicleNum" max-length="50" />
          </page-form-item>
          <page-form-item
            field="vehicleType"
            label="设备类型"
            :required="equipment_type_must == 1 ? true : false"
            :rules="[{ required: equipment_type_must == 1 ? true : false, message: '请选择设备类型', trigger: 'change' }]"
          >
            <sysdict-select
              v-model="form.vehicleType"
              code="equipment_type"
              @mustGet="
                (code, must) => {
                  equipment_type_must = must
                }
              "
            />
          </page-form-item>
          <page-form-item
            field="vehicleFirm"
            label="设备品牌"
            required
            :rules="[{ required: true, message: '请选择设备品牌', trigger: 'change' }]"
          >
            <a-select placeholder="请选择" v-model="form.vehicleFirm" @change="vehicleFirmChange">
              <a-option v-for="item of enums.vehicleFirmMap" :value="item.value" :label="item.name">{{ item.name }}</a-option>
            </a-select>
          </page-form-item>
          <page-form-item
            field="vehicleModel"
            label="设备型号"
            :required="equipment_brand_must == 1 ? true : false"
            :rules="[{ required: equipment_brand_must == 1 ? true : false, message: '请选择设备型号', trigger: 'change' }]"
          >
            <sysdict-select
              v-model="form.vehicleModel"
              code="equipment_brand"
              allow-clear
              @mustGet="
                (code, must) => {
                  equipment_brand_must = must
                }
              "
            />
          </page-form-item>
          <page-form-item
            style="position: relative"
            label-component="div"
            field="supplierId"
            label="设备供应商"
            required
            :rules="[{ required: true, message: '请选择设备供应商', trigger: 'change' }]"
          >
            <template #label-extra>
              <!-- 新增供应商 -->
              <i-add-supplier typeText="设备" supplierType="5" @addOk="addOk" />
            </template>
            <a-select placeholder="请选择" v-model="form.supplierId">
              <a-option v-for="item of supplierList" :value="item.id" :label="item.supplierName">{{ item.supplierName }}</a-option>
            </a-select>
          </page-form-item>
          <page-form-item field="connectionMode" label="接电方式">
            <sysdict-select v-model="form.connectionMode" code="connection_mode" allow-clear />
          </page-form-item>
          <page-form-item field="vin" label="安装车辆">
            <a-select
              v-model="form.vin"
              :loading="vinloading"
              placeholder="请选择"
              allow-search
              @search="handleSearch"
              @blur="handleSearch(($event = ''))"
              :filter-option="false"
              allow-clear
            >
              <a-option v-for="item of carList" :value="item.vin">{{ item.licenseNo }}</a-option>
            </a-select>
          </page-form-item>
          <page-form-item field="installer" label="安装人">
            <remote-select
              v-model="form.installer"
              placeholder="请选择"
              type="store_staff_list"
              :initStr="form.installerName"
              @change="installerChange"
              :params="{
                oldIdList: employeeId ? [employeeId] : undefined,
              }"
            />
          </page-form-item>
          <page-form-item field="installationSite" label="安装位置">
            <i-input placeholder="请输入" v-model="form.installationSite" :max-length="50" />
          </page-form-item>
          <page-form-item field="installationTime" label="安装时间">
            <i-date-picker show-time value-format="YYYY-MM-DD HH:mm:ss" class="w-full" v-model="form.installationTime" allow-clear />
          </page-form-item>
          <page-form-item
            v-if="codeShow"
            field="vehicleCode"
            label="驭联code码"
            labelTooltipContent="驭联GPS设备上如有code码，请将其填写进系统，否者系统无法识别GPS设备"
          >
            <i-input placeholder="请输入" v-model="form.vehicleCode" max-length="30" />
          </page-form-item>
          <page-form-item field="remark" label="GPS备注" size="2/3">
            <a-textarea placeholder="请输入" v-model="form.remark" auto-size max-length="200" />
          </page-form-item>
          <page-form-item field="installationPhotoList" label="安装照片" size="1">
            <upload-img limit="8" v-model="form.installationPhotoList" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" />
</template>

<script setup name="CarVehicleForm">
  import useNavigate from '@/hooks/useNavigate'
  import { onMounted, ref } from 'vue'
  import { getEnums, vehicleSupplier, getCar, findUserInfo, vehicleDetail, vehicleAdd, vehicleEdit } from '@/api/asset/vehicle'
  import dayjs from 'dayjs'

  import { useRoute } from 'vue-router'

  const { navigateBack } = useNavigate()
  const route = useRoute()
  const routePrams = route.params

  const form = ref({
    installationTime: '',
  })

  const equipment_type_must = ref(null) //设备类型是否必填
  const equipment_brand_must = ref(null) //设备型号是否必填

  // 选择安装人后被重置问题
  const installerChange = (val, option) => {
    form.value.installerName = option.realname
  }

  const enums = ref([])
  const getPageEnums = () => {
    getEnums().then((res) => {
      enums.value = res.result
    })
  }

  // 获取供应商
  const supplierList = ref([])
  const getSupplier = () => {
    vehicleSupplier({ supplierType: 5, status: 1 }).then((res) => {
      supplierList.value = res.result
    })
  }

  // 添加供应商成功
  const addOk = (id) => {
    form.value.supplierId = id
    getSupplier()
  }

  // 获取 安装车辆
  const carList = ref([])
  const vinloading = ref(false)
  const handleSearch = (e) => {
    vinloading.value = true
    getCar({ licenseNoLike: e, operateStatusList: [10, 20, 30, 50], tenantId: tenantId.value, pageNumber: 1, pageSize: 10 }).then((res) => {
      carList.value = res.result
      vinloading.value = false
    })
  }

  const getDates = () => {
    form.value.installationTime = dayjs(getNowDate(0)).format('YYYY-MM-DD HH:mm:ss')
  }

  const codeShow = ref(false)
  const vehicleFirmChange = (e) => {
    console.log(e)
    if (e == '驭联') {
      codeShow.value = true
    } else {
      codeShow.value = false
    }
  }

  // 获取当前用户
  const employeeId = ref(null)
  const tenantId = ref(null)
  const getUserInfo = () => {
    findUserInfo().then((res) => {
      tenantId.value = res.result.tenantId
      employeeId.value = res.result.employeeId
      if (employeeId.value && pageType.value == 'create') {
        form.value.installer = Number(employeeId.value) //默认当前登陆人
      }
    })
  }

  // 编辑获取详情
  const getDetail = (id) => {
    vehicleDetail({ id: id }).then((res) => {
      form.value = res.result
      if (res.result.licenseNo) {
        vinloading.value = true
        findUserInfo().then((ress) => {
          getCar({
            licenseNoLike: res.result.licenseNo,
            operateStatusList: [10, 20, 30, 50],
            tenantId: ress.result.tenantId,
            pageNumber: 1,
            pageSize: 10,
          }).then((resss) => {
            carList.value = resss.result
            vinloading.value = false
          })
        })
      }
      if (form.value.vehicleFirm == '驭联') {
        codeShow.value = true
      }
    })
  }

  // 默认日期时间
  const getNowDate = (n) => {
    console.log(n)
    var timestamp = Date.parse(new Date())
    timestamp = timestamp / 1000
    timestamp += Number(n) * 86400
    var newTime = new Date(timestamp * 1000)
    console.log(newTime)
    return newTime
  }

  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        if (pageType.value == 'create') {
          vehicleAdd({ ...form.value })
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        } else {
          vehicleEdit({ ...form.value })
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        }
      }
    })
  }
  const pageType = ref('')
  onMounted(() => {
    const id = routePrams.id
    if (id) {
      getDetail(id)
      pageType.value = 'edit'
    } else {
      pageType.value = 'create'
    }
    getUserInfo()
    getPageEnums()
    getSupplier()
    handleSearch('')
    getDates()
  })
</script>

<style lang="less" scoped>
  :deep(.upload-item) {
    margin: 0px 16px 0 0;
  }
  .textarea-in {
    width: 100%;
    height: 100px;
  }
  .operate-list {
    position: absolute;
    right: -236px;
    margin-left: -40px;

    .operate-btn + .operate-btn {
      margin-left: 16px;
    }
  }

  .upload-wrapper {
    padding: 20px 0 0;

    .upload-content {
      width: 40%;
      margin-right: 40px;
    }
  }
</style>
